package cn.ilovese.collect.serviceimpl.user;

import cn.ilovese.collect.controller.socket.WebSocketServer;
import cn.ilovese.collect.datamapper.device.DeviceMapper;
import cn.ilovese.collect.datamapper.device.DeviceRequirementMapper;
import cn.ilovese.collect.datamapper.report.ReportMapper;
import cn.ilovese.collect.datamapper.report.ScoreMapper;
import cn.ilovese.collect.datamapper.task.TaskMapper;
import cn.ilovese.collect.datamapper.user.ActivityMapper;
import cn.ilovese.collect.datamapper.user.InviteMapper;
import cn.ilovese.collect.datamapper.user.UserMapper;
import cn.ilovese.collect.datamapper.work.WorkMapper;
import cn.ilovese.collect.datamapper.workermessage.WorkerMessageMapper;
import cn.ilovese.collect.po.device.Device;
import cn.ilovese.collect.po.report.Report;
import cn.ilovese.collect.po.report.Score;
import cn.ilovese.collect.po.task.Task;
import cn.ilovese.collect.po.user.Activity;
import cn.ilovese.collect.po.user.Invite;
import cn.ilovese.collect.po.user.User;
import cn.ilovese.collect.po.work.Work;
import cn.ilovese.collect.po.workermessage.WorkerMessage;
import cn.ilovese.collect.service.user.MessageService;
import cn.ilovese.collect.service.user.UserService;

import cn.ilovese.collect.util.Constant;
import cn.ilovese.collect.util.MyDateUtil;
import cn.ilovese.collect.vo.Device.DeviceRequirementVO;
import cn.ilovese.collect.vo.Device.DeviceVO;
import cn.ilovese.collect.vo.InviteGroupVO;
import cn.ilovese.collect.vo.NullVO;
import cn.ilovese.collect.vo.ResultVO;
import cn.ilovese.collect.vo.report.ReportVO;
import cn.ilovese.collect.vo.report.ScoreAllVO;
import cn.ilovese.collect.vo.report.ScoreVO;
import cn.ilovese.collect.vo.statistic.DataVisualizationVO;
import cn.ilovese.collect.vo.statistic.StatisticItemVO;
import cn.ilovese.collect.vo.task.TaskVO;
import cn.ilovese.collect.vo.task.TaskWithUsernameVO;
import cn.ilovese.collect.vo.user.MessageFormVO;
import cn.ilovese.collect.vo.user.UserVO;
import cn.ilovese.collect.vo.user.WorkerInfoVO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    // @Resource标识特定的目标组件，你们自己添加，类似软工二
    // @Autowired装载java bean，用于set方法，你们自己添加，类似软工二
    //注意在这里添加每个实现方法的说明注释，类似以下
    /**
     * 这个方法干了什么
     *
     * @param 参数1 解释
     * @param 参数2 解释
     * ......
     * @return 返回值解释
     */
    @Resource
    UserMapper userMapper;

    @Resource
    ActivityMapper activityMapper;

    @Resource
    InviteMapper inviteMapper;

    @Resource
    TaskMapper taskMapper;

    @Resource
    WorkerMessageMapper workerMessageMapper;

    @Resource
    WorkMapper workMapper;

    @Resource
    ReportMapper reportMapper;

    @Resource
    ScoreMapper scoreMapper;

    @Resource
    DeviceMapper deviceMapper;

    @Resource
    DeviceRequirementMapper deviceRequirementMapper;

    @Override
    public ResultVO<UserVO> userRegister(UserVO vo){
        String name = vo.getUsername();
        if(userMapper.selectByUsername(name) != null){
            return new ResultVO<>(Constant.REQUEST_FAIL, "这个用户名已经注册过账号！");
        }
        else if(userMapper.selectByEmail(vo.getEmail()) != null){
            System.out.println(vo.getEmail());
            return new ResultVO<>(Constant.REQUEST_FAIL, "这个邮箱已经注册过账号！");
        }
        User user = new User(vo);
        user.setFreqDevice(" ");
        user.setSkill(" ");
        user.setTaskPrefer(" ");
        int id = userMapper.insert(user);
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL, "插入失败");
        else{
            UserVO res = new UserVO(userMapper.selectByUsername(name));
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"账号注册成功",res);
        }
    }
    @Override
    public ResultVO<UserVO> userLogin(String username, String password){
        User user = userMapper.selectByUsername(username);
        if(user == null)
            return new ResultVO<>(Constant.REQUEST_FAIL, "用户不存在");
        else{
            String stored_pwd = user.getPassword();
            if(!stored_pwd.equals(password))
                return new ResultVO<>(Constant.REQUEST_FAIL, "密码错误");
        }
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(nowTime);
        Activity loginRecord=activityMapper.selectByUserIdAndLoginDate(user.getId(),nowDate);
        if(loginRecord==null) {
            Activity newRecord=new Activity();
            newRecord.setUserId(user.getId());
            newRecord.setLoginDate(nowDate);
            newRecord.setActivityCount(1);
            activityMapper.insert(newRecord);
        }
        List<String> recommend=getRecommendCharacters(user.getId());
        UserVO res=new UserVO(user);
        res.setRecommendSkill(recommend.get(0));
        res.setRecommendPrefer(recommend.get(1));
        res.setRecommendDevice(recommend.get(2));
        //System.out.println("推荐设备："+res.getRecommendDevice());
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"登陆成功",res);
    }

    @Override
    public ResultVO<UserVO> userLoginWithEmail(String email, String password){
        User user = userMapper.selectByEmail(email);
        if(user == null)
            return new ResultVO<>(Constant.REQUEST_FAIL, "邮箱不存在");
        else{
            String stored_pwd = user.getPassword();
            if(!stored_pwd.equals(password))
                return new ResultVO<>(Constant.REQUEST_FAIL, "密码错误");
        }
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdf.format(nowTime);
        Activity loginRecord=activityMapper.selectByUserIdAndLoginDate(user.getId(),nowDate);
        if(loginRecord==null) {
            Activity newRecord=new Activity();
            newRecord.setUserId(user.getId());
            newRecord.setLoginDate(nowDate);
            newRecord.setActivityCount(1);
            activityMapper.insert(newRecord);
        }
        List<String> recommend=getRecommendCharacters(user.getId());
        UserVO res=new UserVO(user);
        res.setRecommendSkill(recommend.get(0));
        res.setRecommendPrefer(recommend.get(1));
        res.setRecommendDevice(recommend.get(2));
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"登陆成功",res);
    }

    @Override
    public UserVO getUser(Integer uid){
        User userFromDB = userMapper.selectByPrimaryKey(uid);
        if(userFromDB == null){
            return new UserVO();
        }else{
            return new UserVO(userFromDB);
        }
    }

    @Override
    public ResultVO<UserVO> updateUserInfo(UserVO userVO) {
        User user = new User(userVO);
        User nowId=userMapper.selectByUsername(userVO.getUsername());
        user.setId(nowId.getId());
        user.setPassword(nowId.getPassword());
        user.setWorkerLevel(nowId.getWorkerLevel());
        user.setBalance(nowId.getBalance());
        int id = userMapper.updateByPrimaryKey(user);
        if(id < 1)
            return new ResultVO<>(Constant.REQUEST_FAIL, "更新失败");
        else{
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"信息更新成功",userVO);
        }
    }
    @Override
    public Map<String, Object> getContributeCount(Integer workerid) {
        Date endDTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(endDTime);
        String startTime = MyDateUtil.getDayAgoOrAfterString(-119);
        List<Activity> activityMap = activityMapper.selectByUserId(workerid);
        List<String> dateList = MyDateUtil.getDayBetweenDates(startTime, endDTime);
        Map<String, Object> dateMap = new HashMap<>();
        for(Activity item : activityMap) {
            dateMap.put(item.getLoginDate(), item.getActivityCount());
        }
        int sum=0;
        List<List<Object>> resultList = new ArrayList<>();
        for(String item : dateList) {
            Integer count = 0;
            if(dateMap.get(item) != null) {
                count = Integer.valueOf(dateMap.get(item).toString());
            }
            List<Object> objectList = new ArrayList<>();
            objectList.add(item);
            objectList.add(count);
            sum=sum+count;
            resultList.add(objectList);
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<String> activityDateList = new ArrayList<>();
        activityDateList.add(startTime);
        activityDateList.add(endTime);
        resultMap.put("activityDate", activityDateList);
        resultMap.put("activityCount", resultList);
        resultMap.put("sum",sum);
        return resultMap;
    }

    @Override
    public ResultVO<Integer> inviteWorkers(InviteGroupVO inviteGroupVO) {
        Integer taskId = inviteGroupVO.getTaskid();
        List<String> workersName = inviteGroupVO.getWorkeridList();
        for(String workerName : workersName){
            Invite invite = new Invite();
            invite.setWorkerId(userMapper.selectByUsername(workerName).getId());
            invite.setTaskId(taskId);
            int res = inviteMapper.insert(invite);
            if(res < 1)
                return new ResultVO<>(Constant.REQUEST_FAIL,"插入失败",-1);
        }
        WorkerMessage message = new WorkerMessage();
        message.setCooReportId(0);
        message.setMessageType(7);
        message.setReportId(1);
        message.setFromRole(0);
        message.setSubmitTime(new Date());
        message.setFromUserId(
                taskMapper.selectByPrimaryKey(inviteGroupVO.getTaskid()).getUserId());
        message.setStatus(0);
        message.setTaskId(inviteGroupVO.getTaskid());
        message.setTaskName(taskMapper.selectByPrimaryKey(inviteGroupVO.getTaskid()).getTaskName());
        for(int i=0;i<inviteGroupVO.getWorkeridList().size();i++) {
            message.setToWorkerId(userMapper.selectByUsername(inviteGroupVO.getWorkeridList().get(i)).getId());
            int messageId = workerMessageMapper.insert(message);
            WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"插入成功",1);
    }

    @Override
    public ResultVO<List<TaskWithUsernameVO>> getInvitedTaskByWorkerId(Integer workerid) {
        List<Invite> invites = inviteMapper.selectByUserId(workerid);
        List<TaskWithUsernameVO> tasks = new ArrayList<>();
        for(Invite invite: invites){
            Task task = taskMapper.selectByPrimaryKey(invite.getTaskId());
            if(task == null)
                return new ResultVO<>(Constant.REQUEST_FAIL,"没有指定的报告",tasks);
            TaskWithUsernameVO taskTemp=new TaskWithUsernameVO(task,"worker_invited");
            taskTemp.setDeviceRequirement(new DeviceRequirementVO(deviceRequirementMapper.selectByTask(task.getId())));
            List<Device> userDeviceList=deviceMapper.selectByUserId(workerid);
            boolean capableToClaim=false;
            if(userDeviceList!=null) {
                for (Device device : userDeviceList) {
                    if (device.getRam() >= taskTemp.getDeviceRequirement().getMinRam()
                            && device.getRam() >= taskTemp.getDeviceRequirement().getMaxRam()
                            && taskTemp.getDeviceRequirement().getOsList().contains(device.getOs())
                            && taskTemp.getDeviceRequirement().getProcessorArchitectureList().contains(device.getProcessorArchitecture())
                    ) {
                        capableToClaim = true;
                        break;
                    }
                }
            }
            taskTemp.setCapableToClaim(capableToClaim);
            tasks.add(taskTemp);
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取成功",tasks);
    }

    @Override
    public ResultVO<WorkerInfoVO> getWorkerInfo(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null)
            return new ResultVO<>(Constant.REQUEST_FAIL, "该用户不存在");
        WorkerInfoVO res=new WorkerInfoVO(user);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取用户信息成功",res);
    }

    @Override
    public ResultVO<List<DeviceVO>> getUserDevices(Integer userId) {
        List<Device> devices=deviceMapper.selectByUserId(userId);
        List<DeviceVO> res=new ArrayList<>();
        for(Device device: devices){
            res.add(new DeviceVO(device));
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取设备列表成功",res);
    }

    @Override
    public ResultVO<DeviceVO> createOrUpdateDevice(Integer userId, DeviceVO device) {
        device.setUserId(userId);
        Device newDevice = new Device(device);
        if(device.getId() < 0){
            int id = deviceMapper.insert(newDevice);
            if(id < 1)
                return new ResultVO<>(Constant.REQUEST_FAIL, "插入新设备失败");
            else{
                DeviceVO res = new DeviceVO(newDevice);
                res.setId(id);
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"插入新设备成功",res);
            }
        }else{
            deviceMapper.updateByPrimaryKey(newDevice);
            DeviceVO res = new DeviceVO(newDevice);
            return new ResultVO<>(Constant.REQUEST_SUCCESS, "添加成功", res);
        }

    }

    @Override
    public ResultVO<NullVO> dropDevice(Integer deviceId) {
        int id=deviceMapper.deleteByPrimaryKey(deviceId);
        if(id<1)
            return new ResultVO<>(Constant.REQUEST_FAIL,"删除设备失败");
        else{
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"插入新设备成功",new NullVO());
        }
    }

    @Override
    public ResultVO<List<DataVisualizationVO>> getStatisticGraph(String graphName) {
        System.out.println(graphName);
        DataVisualizationVO dataVisualization=new DataVisualizationVO();
        dataVisualization.setItems(new ArrayList<>());
        List<DataVisualizationVO> res=new ArrayList<>();
        StatisticItemVO bossStatistic=new StatisticItemVO();
        bossStatistic.setName("发包方");
        bossStatistic.setValue(userMapper.selectByRole("boss").size());
        StatisticItemVO workerStatistic=new StatisticItemVO();
        workerStatistic.setName("众包工人");
        workerStatistic.setValue(userMapper.selectByRole("worker").size());
        switch (graphName){
            case "graph1":
                dataVisualization.getItems().add(bossStatistic);
                dataVisualization.getItems().add(workerStatistic);
                res.add(dataVisualization);
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取graph1数据成功", res);
            case "graph2":
                workerStatistic.setName("现有众包工人");
                dataVisualization.getItems().add(bossStatistic);
                dataVisualization.getItems().add(workerStatistic);
                StatisticItemVO taskStatistic=new StatisticItemVO();
                taskStatistic.setName("现有任务");
                taskStatistic.setValue(taskMapper.selectAll().size());
                dataVisualization.getItems().add(taskStatistic);
                StatisticItemVO activeWorkerStatistic=new StatisticItemVO();
                activeWorkerStatistic.setName("活跃众包工人");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date nowTime=new Date();
                String nowDate = sdf.format(nowTime);
                activeWorkerStatistic.setValue(activityMapper.selectThirtyDaysActiveUser(nowDate));
                dataVisualization.getItems().add(activeWorkerStatistic);
                res.add(dataVisualization);
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取graph2数据成功", res);
            case "graph3":
                List<Device> windowsDevice=deviceMapper.selectWindows();
                List<Device> iosDevice=deviceMapper.selectIOS();
                List<Device> androidDevice=deviceMapper.selectAndroid();
                List<Device> harmonyDevice=deviceMapper.selectHarmony();
                StatisticItemVO windowsStatistic=new StatisticItemVO();
                windowsStatistic.setName("Windows设备");
                windowsStatistic.setValue(windowsDevice.size());
                StatisticItemVO androidStatistic=new StatisticItemVO();
                androidStatistic.setName("Android设备");
                androidStatistic.setValue(androidDevice.size());
                StatisticItemVO iosStatistic=new StatisticItemVO();
                iosStatistic.setName("ios设备");
                iosStatistic.setValue(iosDevice.size());
                StatisticItemVO harmonyStatistic=new StatisticItemVO();
                harmonyStatistic.setName("Harmony设备");
                harmonyStatistic.setValue(harmonyDevice.size());
                DataVisualizationVO withoutVersion=new DataVisualizationVO();
                withoutVersion.setItems(new ArrayList<>());
                withoutVersion.getItems().add(windowsStatistic);
                withoutVersion.getItems().add(iosStatistic);
                withoutVersion.getItems().add(harmonyStatistic);
                withoutVersion.getItems().add(androidStatistic);
                StatisticItemVO windowsXPStatistic=new StatisticItemVO();
                windowsXPStatistic.setName("windowsXP");
                windowsXPStatistic.setValue(deviceMapper.selectWindowsXP().size());
                StatisticItemVO windows7Statistic=new StatisticItemVO();
                windows7Statistic.setName("windows7");
                windows7Statistic.setValue(deviceMapper.selectWindows7().size());
                StatisticItemVO windows10Statistic=new StatisticItemVO();
                windows10Statistic.setName("windows10");
                windows10Statistic.setValue(deviceMapper.selectWindows10().size());
                StatisticItemVO windows11Statistic=new StatisticItemVO();
                windows11Statistic.setName("windows11");
                windows11Statistic.setValue(deviceMapper.selectWindows11().size());
                StatisticItemVO iOS12Statistic=new StatisticItemVO();
                iOS12Statistic.setName("iOS12");
                iOS12Statistic.setValue(deviceMapper.selectiOS12().size());
                StatisticItemVO iOS13Statistic=new StatisticItemVO();
                iOS13Statistic.setName("iOS13");
                iOS13Statistic.setValue(deviceMapper.selectiOS13().size());
                StatisticItemVO iOS14Statistic=new StatisticItemVO();
                iOS14Statistic.setName("iOS14");
                iOS14Statistic.setValue(deviceMapper.selectiOS14().size());
                StatisticItemVO iOS15Statistic=new StatisticItemVO();
                iOS15Statistic.setName("iOS15");
                iOS15Statistic.setValue(deviceMapper.selectiOS15().size());
                StatisticItemVO Android12Statistic=new StatisticItemVO();
                Android12Statistic.setName("Android12");
                Android12Statistic.setValue(deviceMapper.selectAndroid12().size());
                StatisticItemVO Android11Statistic=new StatisticItemVO();
                Android11Statistic.setName("Android11");
                Android11Statistic.setValue(deviceMapper.selectAndroid11().size());
                StatisticItemVO Android10Statistic=new StatisticItemVO();
                Android10Statistic.setName("Android10");
                Android10Statistic.setValue(deviceMapper.selectAndroid10().size());
                StatisticItemVO Android9Statistic=new StatisticItemVO();
                Android9Statistic.setName("Android9");
                Android9Statistic.setValue(deviceMapper.selectAndroid9().size());
                StatisticItemVO Android8Statistic=new StatisticItemVO();
                Android8Statistic.setName("Android8");
                Android8Statistic.setValue(deviceMapper.selectAndroid8().size());
                StatisticItemVO HarmonyOS1Statistic=new StatisticItemVO();
                HarmonyOS1Statistic.setName("HarmonyOS1");
                HarmonyOS1Statistic.setValue(deviceMapper.selectHarmonyOS1().size());
                StatisticItemVO HarmonyOS2Statistic=new StatisticItemVO();
                HarmonyOS2Statistic.setName("HarmonyOS2");
                HarmonyOS2Statistic.setValue(deviceMapper.selectHarmonyOS2().size());
                StatisticItemVO HarmonyOS3Statistic=new StatisticItemVO();
                HarmonyOS3Statistic.setName("HarmonyOS3");
                HarmonyOS3Statistic.setValue(deviceMapper.selectHarmonyOS3().size());
                DataVisualizationVO withVersion=new DataVisualizationVO();
                withVersion.setItems(new ArrayList<>());
                withVersion.getItems().add(windowsXPStatistic);
                withVersion.getItems().add(windows7Statistic);
                withVersion.getItems().add(windows10Statistic);
                withVersion.getItems().add(windows11Statistic);
                withVersion.getItems().add(iOS12Statistic);
                withVersion.getItems().add(iOS13Statistic);
                withVersion.getItems().add(iOS14Statistic);
                withVersion.getItems().add(iOS15Statistic);
                withVersion.getItems().add(Android12Statistic);
                withVersion.getItems().add(Android11Statistic);
                withVersion.getItems().add(Android10Statistic);
                withVersion.getItems().add(Android9Statistic);
                withVersion.getItems().add(Android8Statistic);
                withVersion.getItems().add(HarmonyOS1Statistic);
                withVersion.getItems().add(HarmonyOS2Statistic);
                withVersion.getItems().add(HarmonyOS3Statistic);
                res.add(withoutVersion);
                res.add(withVersion);
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取graph3数据成功", res);
            case "graph4":
                StatisticItemVO functionTest=new StatisticItemVO();
                functionTest.setName("功能测试");
                functionTest.setValue(taskMapper.selectFunctionTest().size());
                StatisticItemVO performanceTest=new StatisticItemVO();
                performanceTest.setName("性能测试");
                performanceTest.setValue(taskMapper.selectPerformanceTest().size());
                StatisticItemVO bugExploration=new StatisticItemVO();
                bugExploration.setName("Bug探索");
                bugExploration.setValue(taskMapper.selectBugExploration().size());
                dataVisualization.getItems().add(functionTest);
                dataVisualization.getItems().add(performanceTest);
                dataVisualization.getItems().add(bugExploration);
                res.add(dataVisualization);
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取graph4数据成功", res);
            default:
                return new ResultVO<>(Constant.REQUEST_FAIL,"获取可视化图表失败，图表名错误");
        }
    }

    @Override
    public ResultVO<NullVO> sendMessageToUser(MessageFormVO messageFormVO) {
        WorkerMessage message = new WorkerMessage();
        message.setCooReportId(1);
        message.setMessageType(8);
        message.setReportId(1);
        message.setFromRole(1);
        message.setSubmitTime(new Date());
        message.setFromUserId(messageFormVO.getSourceUserId());
        message.setToWorkerId(messageFormVO.getTargetUserId());
        message.setStatus(0);
        message.setTaskId(messageFormVO.getRelatedSubTaskId());
        message.setTaskName(taskMapper.selectByPrimaryKey(messageFormVO.getRelatedSubTaskId()).getTaskName());
        message.setMsgContent(messageFormVO.getMessageContent());
        int messageId = workerMessageMapper.insert(message);
        if(messageId<=0)
            return new ResultVO<>(Constant.REQUEST_FAIL,"发送消息失败，请重新发送");
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"发送消息成功", new NullVO());
    }

    @Override
    public ResultVO<NullVO> sendRemindMessageToUser(MessageFormVO messageFormVO) {
        WorkerMessage message = new WorkerMessage();
        message.setCooReportId(1);
        message.setMessageType(9);
        message.setReportId(1);
        message.setFromRole(1);
        message.setSubmitTime(new Date());
        message.setFromUserId(messageFormVO.getSourceUserId());
        message.setToWorkerId(messageFormVO.getTargetUserId());
        message.setStatus(0);
        message.setTaskId(messageFormVO.getRelatedSubTaskId());
        message.setTaskName(taskMapper.selectByPrimaryKey(messageFormVO.getRelatedSubTaskId()).getTaskName());
        int messageId = workerMessageMapper.insert(message);
        if(messageId<=0)
            return new ResultVO<>(Constant.REQUEST_FAIL,"发送提醒失败，请重新发送");
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0, message.getToWorkerId()), message.getToWorkerId());
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"发送提醒成功", new NullVO());
    }

    @Override
    public ResultVO<List<UserVO>> getAllWorkers() {
        List<User> users = userMapper.selectByRole("worker");
        List<UserVO> res = new ArrayList<>();
        for(User user: users){
            res.add(new UserVO((user)));
        }
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取所有工人信息成功",res);
    }

    List<String> getRecommendCharacters(Integer uid){
        List<String> res=new ArrayList<>();
        List<Work> workList=workMapper.selectByWorker(uid);
        int[] preferNums=new int[3];
        int[] envNums=new int[4];
        Double[] skillNums=new Double[3];
        for(int i=0;i<3;i++){
            preferNums[i]=0;
            envNums[i]=0;
            skillNums[i]=0.0;
        }
        envNums[3]=0;
        for(Work work:workList){
            Task taskTemp=taskMapper.selectByPrimaryKey(work.getTaskId());
            switch (taskTemp.getType()){
                case "function_test":
                    preferNums[0]++;
                    break;
                case "performance_test":
                    preferNums[1]++;
                    break;
                case "bug_explore":
                    preferNums[2]++;
                    break;
                default:
                    break;
            }
        }
        List<Report> reportList=reportMapper.selectByUser(uid);
        for(Report report:reportList){
            Integer taskId = report.getTaskId();
            String type = "";
            if(taskId == null)
                continue;
            type=taskMapper.selectByPrimaryKey(report.getTaskId()).getType();
            switch (type){
                case "function_test":
                    skillNums[0]=skillNums[0]+getScoresOfReport(report.getId());
                    break;
                case "performance_test":
                    skillNums[1]=skillNums[1]+getScoresOfReport(report.getId());
                    break;
                case "bug_explore":
                    skillNums[2]=skillNums[2]+getScoresOfReport(report.getId());
                    break;
                default:
                    break;
            }
            switch (report.getDeviceInfo()){
                case "iOS12.x":
                case "iOS13.x":
                case "iOS14.x":
                case "iOS15.x":
                    envNums[0]++;
                    break;
                case "Android12":
                case "Android11":
                case "Android10":
                case "Android9":
                case "Android8":
                    envNums[1]++;
                    break;
                case "HarmonyOS1.x":
                case "HarmonyOS2.x":
                    envNums[2]++;
                    break;
                case "windowsXP":
                case "windows7":
                case "windows10":
                case "windows11":
                    envNums[3]++;
                    break;
                default:
                    break;
            }
        }
        skillNums[0]=skillNums[0]/reportList.size();
        skillNums[1]=skillNums[1]/reportList.size();
        skillNums[2]=skillNums[2]/reportList.size();
        if(skillNums[0]>skillNums[1]&&skillNums[0]>skillNums[2])
            res.add("function_test");
        else if(skillNums[1]>skillNums[0]&&skillNums[1]>skillNums[2])
            res.add("performance_test");
        else if(skillNums[2]>skillNums[0]&&skillNums[2]>skillNums[1])
            res.add("bug_explore");
        else
            res.add(" ");
        if(preferNums[0]>preferNums[1]&&preferNums[0]>preferNums[2])
            res.add("function_test");
        else if(preferNums[1]>preferNums[0]&&preferNums[1]>preferNums[2])
            res.add("performance_test");
        else if(preferNums[2]>preferNums[0]&&preferNums[2]>preferNums[1])
            res.add("bug_explore");
        else
            res.add(" ");
        if(envNums[0]>envNums[1]&&envNums[0]>envNums[2]&&envNums[0]>envNums[3])
            res.add("iOS");
        else if(envNums[1]>envNums[0]&&envNums[1]>envNums[2]&&envNums[1]>envNums[3])
            res.add("Android");
        else if(envNums[2]>envNums[0]&&envNums[2]>envNums[1]&&envNums[2]>envNums[3])
            res.add("HarmonyOS");
        else if(envNums[3]>envNums[0]&&envNums[3]>envNums[1]&&envNums[3]>envNums[2])
            res.add("Windows");
        else
            res.add(" ");
        return res;
    }

    public Double getScoresOfReport(Integer reportid) {
        List<Score> temp = scoreMapper.selectByReportId(reportid);
        if(temp.size() == 0)
            return 0.0;

        Double sum= Double.valueOf(0);
        for(int i=0;i<temp.size();i++){
            sum=sum+temp.get(i).getScore();
        }
        sum=sum/temp.size();
        return sum;
    }
}
